package com.ckf.es.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.ckf.es.entity.Nba;
import com.ckf.es.mapper.EmpMapper;
import com.ckf.es.service.EmpService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: serene
 * @date: 2020/10/29 9:22
 */

@Service
public class EmpServiceImpl implements EmpService {

    /**
     * 定义索引库
     */
    private static final String NBA_INDEX = "nba_last";

    @Resource
    private RestHighLevelClient client;

    @Autowired
    private EmpMapper empMapper;

    /**
     * 将数据库中的数据全部导入到ES
     *
     * @return
     * @throws IOException
     */
    @Override
    public boolean importAll() throws IOException {
        List<Nba> list = empMapper.selectEmpAll();
        for (Nba player : list) {
            addPlayer(player, String.valueOf(player.getId()));
        }
        return true;
    }


    /**
     * 添加
     *
     * @param player 实体类
     * @param id     编号
     * @return
     * @throws IOException
     */
    @Override
    public boolean addPlayer(Nba player, String id) throws IOException {
        IndexRequest request = new IndexRequest(NBA_INDEX).id(id).source(beanToMap(player));
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
        return false;
    }

    /**
     * 对象转map
     *
     * @param bean
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                if (beanMap.get(key) != null) {
                    map.put(key + "", beanMap.get(key));
                }
            }
        }
        return map;
    }


}
